package aoi.movieweb.Controller;

import aoi.movieweb.model.Movie;
import aoi.movieweb.service.FileStorageService;
import aoi.movieweb.service.MovieService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
@RequestMapping("/api/movie")
public class ControllerMovie {

    private final MovieService movieService;
    private final FileStorageService fileStorageService;
    private final String uploadDir;

    @Autowired
    public ControllerMovie(MovieService movieService, FileStorageService fileStorageService,
                           @Value("${file.upload-dir}") String uploadDir) {
        this.movieService = movieService;
        this.fileStorageService = fileStorageService;
        this.uploadDir = uploadDir;
    }

    // 添加电影
    @PostMapping
    public ResponseEntity<?> addMovie(@Valid @RequestBody Movie movie, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseEntity.badRequest().body(bindingResult.getAllErrors());
        }
        Movie savedMovie = movieService.addMovie(movie);
        return ResponseEntity.status(HttpStatus.CREATED).body(savedMovie); // 返回201状态
    }

    // 获取所有电影
    @GetMapping
    public ResponseEntity<List<Movie>> getAllMovies() {

        List<Movie> movies = movieService.getAllMovies();
        return movies.isEmpty() ? ResponseEntity.noContent().build() : ResponseEntity.ok(movies);
    }

    // 获取电影详情
    @GetMapping("/{id}")
    public ResponseEntity<?> getMovie(@PathVariable Long id) {
        Movie movie = movieService.findById(id);
        return movie != null ? ResponseEntity.ok(movie) : ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body("Movie not found");
    }


    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteMovie(@PathVariable Long id) {
        movieService.deleteMovie(id);
        return ResponseEntity.noContent().build();
    }

    // 上传电影海报
    @PostMapping("/{id}/upload")
    public ResponseEntity<?> uploadMoviePoster(@PathVariable Long id, @RequestParam("file") MultipartFile file) {
        Movie movie = movieService.findById(id);
        if (movie == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Movie not found");
        }

        try {
            String fileName = fileStorageService.storeFile(file);
            movie.setPosterUrl("api/movie/poster/" + fileName);
            movieService.addMovie(movie);
            return ResponseEntity.ok("文件上传成功: " + fileName);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Upload failed: " + e.getMessage());
        }
    }

    // 下载电影海报
    @GetMapping("/poster/{fileName:.+}")
    public ResponseEntity<?> downloadMoviePoster(@PathVariable String fileName) {
        try {
            Path filePath = Paths.get(uploadDir).resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());

            if (resource.exists() || resource.isReadable()) {
                return ResponseEntity.ok()
                        .contentType(MediaType.parseMediaType(Files.probeContentType(filePath)))
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Download failed: " + e.getMessage());
        }
    }
}

